import {xhrGet} from "@/services";
import {generateCacheRequestFunction} from "@/common-data-source/WithCache";
import {TSelectOptions} from "@/common-data-source/type";
import {useEffect, useState} from "react";

/**
 * @author DongPing
 * 2022/1/18 11:30
 *
 * 数据字典查询
 *
 * */

/**
 * 查询数据字典下拉选项
 * */
export const queryDictionaryForSelect = generateCacheRequestFunction<TSelectOptions, string>(function (dictType) {
	return xhrGet('/sym/dict/findValues', {code: dictType})
		.then((res: any) => {
			return res.result.map((item: any) => {
				return {name: item.name, value: item.code}
			})
		})
});

/**
 * 数据字典下拉选项hook
 * */
export function useDictionaryOptions(dictType: string, onlyFirstLevel?: boolean) {
	const [options, setOptions] = useState<TSelectOptions>([]);
	useEffect(function () {
		(onlyFirstLevel ? queryDictionaryOnlyFirstLevelForSelect : queryDictionaryForSelect)(dictType)
			.then(setOptions);
	}, [dictType, onlyFirstLevel]);
	return options;
}

/**
 * 查询数据字典下拉选项，只包含一级字典
 *
 * */
export const queryDictionaryOnlyFirstLevelForSelect = generateCacheRequestFunction<TSelectOptions, string>(function (dictType) {
	return xhrGet('/sym/dict/findValues', {code: dictType})
		.then((res: any) => {
			const result: TSelectOptions = [];
			for(const item of res.result) {
				//忽略二级字典
				if(item.parentCode) continue;

				result.push({
					value: item.code,
					name: item.name,
					// @ts-ignore
					code: item.code
				})
			}
			return result;
		})
});



/**
 * 查询子类型的数据字典
 * */
export const queryDictionaryChildrenForSelect = generateCacheRequestFunction<TSelectOptions, {dictType: string, parentCode: string}>(function (p) {
	if(!p.parentCode) return Promise.resolve([]);
	return xhrGet('/sym/dict/findValues', {code: p.dictType, parentCode: p.parentCode})
		.then((res: any) => {
			const result: Array<{name: string ,value: string}> = [];
			for(const item of res.result) {
				result.push({
					name: item.name,
					value: item.code
				})
			}
			return result;
		});
});

/**
 * 数据字典子类型下拉选项hook
 * */
export function useDictionaryChildrenOptions(dictType: string, parentCode: string) {
	const [options, setOptions] = useState<TSelectOptions>([]);
	useEffect(function () {
		queryDictionaryChildrenForSelect({dictType, parentCode})
			.then(setOptions);
	}, [dictType, parentCode]);
	return options;
}
